package com.server.transaction.config;

import com.server.transaction.aspect.SecureInvokeAspect;
import com.server.transaction.factory.GlobalThreadFactory;
import com.server.transaction.mapper.SecureInvokeRecordMapper;
import com.server.transaction.service.SecureInvokeHandle;
import com.server.transaction.service.SecureInvokeRecordService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @title: TransactionAutoConfiguration
 * @author: gyuan
 * @description
 * @date: 2023-11-16 17:27
 */
@Configuration
@MapperScan(basePackageClasses = SecureInvokeRecordMapper.class)
@Import(value = {SecureInvokeAspect.class, SecureInvokeRecordService.class})
@EnableScheduling
public class TransactionAutoConfiguration {

    public ThreadPoolTaskExecutor transactionExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 优雅停机
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置线程工厂类
        executor.setThreadFactory(new GlobalThreadFactory(executor));
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(200);
        executor.setThreadNamePrefix("transaction-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        executor.initialize();
        return executor;
    }

    @Bean
    public SecureInvokeHandle getSecureInvokeHandle(SecureInvokeRecordService secureInvokeRecordService) {
        return new SecureInvokeHandle(secureInvokeRecordService,transactionExecutor());
    }

}
